package com.huawei.lynnbit.tool.cocos.util;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class CmdUtils {
    private static Map<String, String> env = new HashMap<>();

    private static List<String> PATH = Lists.newArrayList("\\jbr", "\\sdk\\default\\hms\\toolchains\\lib", "\\sdk\\default\\openharmony\\previewer\\common\\bin", "\\sdk\\default\\openharmony\\toolchains", "\\jbr\\bin", "\\tools\\ohpm\\bin", "\\tools\\node");

    public static void initEnv(String devEcoInstallPath) {
        Map<String, String> environment = new ProcessBuilder().environment();
        env.put("DEVECO_SDK_HOME", devEcoInstallPath + "\\sdk");
        env.put("JAVA_HOME", devEcoInstallPath + "\\jbr");
        env.put(getPathName(), getRuntimePath(devEcoInstallPath, environment.get(getPathName())) + environment.get(getPathName()));
    }

    private static String getPathName() {
        if (System.getProperty("os.name").toLowerCase().contains("win")) {
            return "Path";
        } else {
            return "PATH";
        }
    }

    private static String getRuntimePath(String devEcoInstallPath, String existPath) {
        List<String> ret = new ArrayList<>();
        for (String path : PATH) {
            if (existPath.contains(devEcoInstallPath + path)) {
                continue;
            }
            ret.add(devEcoInstallPath + path);
        }

        if (CollectionUtils.isEmpty(ret)) {
            return "";
        }
        return StringUtils.join(ret, ";") + ";";
    }

    public static int exec(String dir, String... cmd) throws IOException, InterruptedException {
        Process process = null;
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(cmd);
            Map<String, String> environment = processBuilder.environment();
            environment.putAll(env);
            processBuilder.redirectErrorStream(true);
            if (StringUtils.isNotBlank(dir)) {
                processBuilder.directory(new File(dir));
            }
            process = processBuilder.start();

            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }

            return process.waitFor();
        } finally {
            if (process != null) {
                process.destroy();
            }
        }
    }
}
